package com.house365.im.client;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.PacketExtension;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

import com.house365.core.R;
import com.house365.core.constant.CorePreferences;
import com.house365.core.image.AsyncImageLoader;
import com.house365.core.image.ImageUtil;
import com.house365.core.json.JSONException;
import com.house365.core.json.JSONObject;
import com.house365.core.util.FileUtil;
import com.house365.core.util.store.IOUtil;
import com.house365.im.client.dto.AudioData;
import com.house365.im.client.dto.MessageDto;
import com.house365.im.client.exception.IMManagerNotInitException;
import com.house365.im.client.receiver.HeartbeatReceiver;
import com.house365.im.client.util.LogUtil;
import com.house365.updown.download.DFile;
import com.house365.updown.download.Downloader;
import com.house365.updown.download.Downloader.DownloadCompleteListener;
import com.house365.updown.upload.HttpUploaderManager.OnServerResponse;
import com.house365.updown.upload.UFile;
import com.house365.updown.upload.Uploader;
import com.house365.updown.upload.Uploader.UploadCompleteListener;

/**
 * @Author Rick.Ping
 * @Date 2013-12-13
 * @Comment
 **/
public class IMManager {
	private static final String LOGTAG = LogUtil.makeLogTag(IMManager.class);
	private static IMManager manager;
	private Application context;

	// private BroadcastReceiver notificationReceiver;

//	private BroadcastReceiver heartbeatReceiver;
	private BroadcastReceiver connectivityReceiver;
	private ExecutorService executorService;

	private TaskSubmitter taskSubmitter;

	private static XmppManager xmppManager;

	private SharedPreferences sharedPrefs;

	private IMConfiguration imConfiguration;

	private IMAccount pullAccount;

	private WakeLock wakeLock;
	//
	public final static int CONN_UNAVLIABLE = 1;
	// conn stauts
	public final static int CONN_SUCCESS = 11;
	public final static int CONN_ALREAY = 12;
	// auth stauts
	public final static int AUTH_SUCCESS = 21;
	public final static int AUTH_ALREAY = 22;
	public final static int AUTH_USERNAME_INVLIDATE = 23;
	public final static int AUTH_PASSWORD_INVLIDATE = 24;

	// reg stauts
	public final static int REG_SUCCESS = 21;
	public final static int REG_ALREAY = 22;
	public final static int REG_USERNAME_INVLIDATE = 23;
	public final static int REG_PASSWORD_INVLIDATE = 24;

	// send stauts
	public final static int SEND_SUCCESS = 31;
	public final static int SEND_CONNECT_RESET = 32;
	public final static int SEND_CONTENT_INVLIDATE = 33;

	public static final int WAKE_LOCK_OPEN = 1;
	public static final int WAKE_LOCK_CLOSE = 2;

	// sound
	private static SoundPool soundPool;
	private static HashMap<Integer, Integer> soundPoolMap;
	private Downloader downloader;
	private Uploader uploader;

	private String im_file_dir;
	public static void init(Application context, IMConfiguration imConfiguration) {
		if (manager == null) {
			synchronized (IMManager.class) {
				if (manager == null) {
					manager = new IMManager(context, imConfiguration);
				}
			}
		}
	}

	public static IMManager getIMManager() throws IMManagerNotInitException {
		if (manager == null) {
			throw new IMManagerNotInitException();
		}
		return manager;
	}

	private IMManager(Application context, IMConfiguration imConfiguration) {
		this.context = context;
//		heartbeatReceiver = new HeartbeatReceiver(this);

		executorService = Executors.newSingleThreadExecutor();
		taskSubmitter = new TaskSubmitter(this);

		// configuration
		this.imConfiguration = imConfiguration;

		sharedPrefs = context.getSharedPreferences(
				Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);

		Editor editor = sharedPrefs.edit();

		// prefix
		// server into
		editor.putString(Constants.API_KEY, imConfiguration.getApiKey());
		editor.putString(Constants.VERSION, imConfiguration.getVersion());
		editor.putString(Constants.XMPP_HOST, imConfiguration.getHost());
		editor.putInt(Constants.XMPP_PORT, imConfiguration.getPort());
		editor.putString(Constants.APP_NAME, imConfiguration.getAppName());
		// broadcast class
		editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME,
				imConfiguration.getNotifyDetailClass());
		editor.putInt(Constants.NOTIFICATION_ICON, imConfiguration.getIconId());
		// broadcast action
		editor.putString(Constants.CALLBACK_BROADCAST_ACTION,
				imConfiguration.getBroadcastAction());
		// heartbeat action
		editor.putString(Constants.HEARTBEAT_BROADCAST_ACTION,
				imConfiguration.getHeartbeatAction());
		editor.putString(Constants.ROOT_ACTIVITY,
				imConfiguration.getRootActivity());
		editor.putString(Constants.UPLOAD_URL, imConfiguration.getUploadUrl());
		editor.commit();

		xmppManager = new XmppManager(this);

		soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
		soundPoolMap = new HashMap<Integer, Integer>();
		soundPoolMap.put(AudioData.AUDIO_MESSAGE2,
				soundPool.load(context, R.raw.msg2, 1));
		// soundPoolMap.put(AudioData.AUDIO_MESSAGE, soundPool.load(context,
		// R.raw.msg, 1));
		initDownloader();
		initUploader();

	}

	public static void playSound(int type) {
		AudioManager mgr = (AudioManager) xmppManager.getContext()
				.getSystemService(Context.AUDIO_SERVICE);
		float streamVolumeCurrent = mgr
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		float streamVolumeMax = mgr
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volume = streamVolumeCurrent / streamVolumeMax;
		soundPool.play(soundPoolMap.get(type), volume, volume, 1, 0, 1f);
	}

	public Application getContext() {
		return context;
	}

	public void setContext(Application context) {
		this.context = context;
	}

	public void start() {
		Log.d(LOGTAG, "start()...");
		taskSubmitter.submit(new Runnable() {
			public void run() {
				IMManager.this.startReciver();
			}
		});
	}

	private void startReciver() {
		Log.d(LOGTAG, "IMManager start...");
		// registerNotificationReceiver();
		AlarmManager am = (AlarmManager) getContext().getSystemService(
				getContext().ALARM_SERVICE);
		// 1分钟发送一个心跳注册信息
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
				Constants.HEART_BEAT_INTERVAL * 1000, getHeartbeatIntent());
//		registerHeartbeatReceiver();
	}

	public int login(boolean force) {
		Log.d(LOGTAG, "connect()...");
		pullAccount = getPullAccount();
		Log.d(LOGTAG, "pullAccount()...:" + pullAccount);
		if (pullAccount != null) {
			Log.d(LOGTAG, "pullAccount()...:" + pullAccount.getUsername());
			int result = getXmppManager().ConnectTask(force);
			if (result != CONN_SUCCESS && result != CONN_ALREAY) {
				return result;
			}
			// getXmppManager().RegisterTask(pullAccount.getUsername(),pullAccount.getPassword());
			result = getXmppManager().LoginTask(force,pullAccount.getUsername(),
					pullAccount.getPassword());
			if(result == IMManager.AUTH_SUCCESS){
				getAllMessageOfUser();
			}
			return result;
		} else {
			return AUTH_USERNAME_INVLIDATE;
		}
	}

//	public int loginWithOutHistory() {
//		Log.d(LOGTAG, "connect()...");
//		pullAccount = getPullAccount();
//		Log.d(LOGTAG, "pullAccount()...:" + pullAccount);
//		if (pullAccount != null) {
//			Log.d(LOGTAG, "pullAccount()...:" + pullAccount.getUsername());
//			int result = getXmppManager().ConnectTask(false);
//			if (result != CONN_SUCCESS && result != CONN_ALREAY) {
//				return result;
//			}
//			// getXmppManager().RegisterTask(pullAccount.getUsername(),pullAccount.getPassword());
//			result = getXmppManager().LoginTask(false,pullAccount.getUsername(),
//					pullAccount.getPassword());
//			return result;
//		} else {
//			return AUTH_USERNAME_INVLIDATE;
//		}
//	}

	public void disconnect() {
		Log.d(LOGTAG, "disconnect()...");
		IMManager.this.removeAccount();
		taskSubmitter.submit(new Runnable() {
			public void run() {
				try {
					// IMManager.this.unregisterHeartbeatReceiver();
					// AlarmManager
					// am=(AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE);
					// //1分钟发送一个心跳注册信息
					// am.cancel(getHeartbeatIntent());
					IMManager.this.getXmppManager()
							.terminatePersistentConnection();
				} catch (Exception e) {
					Log.e(LOGTAG, e.getMessage());
				}
			}
		});
	}

	/**
	 * 通知监听
	 */
	// private void registerNotificationReceiver() {
	// IntentFilter filter = new IntentFilter();
	// filter.addAction(Constants.getActionShowNotification(getContext()));
	// getContext().registerReceiver(notificationReceiver, filter);
	// }
	//
	// private void unregisterNotificationReceiver() {
	// getContext().unregisterReceiver(notificationReceiver);
	// }

	/**
	 * 心跳注册监听
	 */
//	private void registerHeartbeatReceiver() {
//		IntentFilter filter = new IntentFilter();
//		filter.addAction(Constants.getActionXMPPHeartbeat(getContext()));
//		getContext().registerReceiver(heartbeatReceiver, filter);
//	}

//	private void unregisterHeartbeatReceiver() {
//		getContext().unregisterReceiver(heartbeatReceiver);
//	}

	/**
	 * 在网络、开机等1等情况下发送心
	 */
//	public void sendHeartbeatBroadcast() {
//		Intent intent = new Intent(
//				Constants.getActionXMPPHeartbeat(getContext()));
//		getContext().sendBroadcast(intent);
//	}

	public boolean sendHeartBeatPkg() {
		return xmppManager.sendHeartBeatPkg();
	}

	public class TaskSubmitter {

		final IMManager imManager;

		public TaskSubmitter(IMManager imManager) {
			this.imManager = imManager;
		}

		@SuppressWarnings("unchecked")
		public Future submit(Runnable task) {
			Future result = null;
			if (!imManager.getExecutorService().isTerminated()
					&& !imManager.getExecutorService().isShutdown()
					&& task != null) {
				result = imManager.getExecutorService().submit(task);
			}
			return result;
		}

	}

	public ExecutorService getExecutorService() {
		return executorService;
	}

	public void setExecutorService(ExecutorService executorService) {
		this.executorService = executorService;
	}

	public TaskSubmitter getTaskSubmitter() {
		return taskSubmitter;
	}

	public void setTaskSubmitter(TaskSubmitter taskSubmitter) {
		this.taskSubmitter = taskSubmitter;
	}

	public static XmppManager getXmppManager() {
		return xmppManager;
	}

	public static void setXmppManager(XmppManager xmppManager) {
		IMManager.xmppManager = xmppManager;
	}

	private PendingIntent getHeartbeatIntent() {
		Intent intent = new Intent(getHeartbeatAction());
		PendingIntent sender = PendingIntent.getBroadcast(getContext(), 0,
				intent, 0);
		return sender;

	}

	public SharedPreferences getSharedPrefs() {
		return sharedPrefs;
	}

	public void setSharedPrefs(SharedPreferences sharedPrefs) {
		this.sharedPrefs = sharedPrefs;
	}

	public void setAccount(IMAccount pullAccount) {
		Log.d(LOGTAG, "setAccount()..." + pullAccount);
		Editor editor = sharedPrefs.edit();
		editor.putString(Constants.XMPP_F_USERNAME, pullAccount.getUsername());
		editor.putString(Constants.XMPP_F_PASSWORD, pullAccount.getPassword());
		editor.commit();
	}

	public void cleanAccount() {
		Editor editor = sharedPrefs.edit();
		editor.remove(Constants.XMPP_F_USERNAME);
		editor.remove(Constants.XMPP_F_PASSWORD);
		editor.commit();
	}

	public void setNotificationEnable(boolean flag) {
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(Constants.SETTINGS_NOTIFICATION_ENABLED, flag);
		editor.commit();
	}

	public void setNotificationSoundEnable(boolean flag) {
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(Constants.SETTINGS_SOUND_ENABLED, flag);
		editor.commit();
	}

	public void setNotificationVibrateEnable(boolean flag) {
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(Constants.SETTINGS_VIBRATE_ENABLED, flag);
		editor.commit();
	}

	public void setNotificationToastEnable(boolean flag) {
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(Constants.SETTINGS_TOAST_ENABLED, flag);
		editor.commit();
	}

	public void setNotificationBroadCastenable(boolean flag) {
		Editor editor = sharedPrefs.edit();
		editor.putBoolean(Constants.SETTINGS_BROADCAST_ENABLED, flag);
		editor.commit();
	}

	private boolean hasPullAccount() {
		return sharedPrefs.contains(Constants.XMPP_F_USERNAME);
	}

	public IMAccount getPullAccount() {
		IMAccount pullAccount = null;
		Log.d(LOGTAG, "hasPullAccount()()..." + hasPullAccount());
		if (hasPullAccount()) {
			pullAccount = new IMAccount(sharedPrefs.getString(
					Constants.XMPP_F_USERNAME, ""), sharedPrefs.getString(
					Constants.XMPP_F_PASSWORD, "123456"));
		}
		return pullAccount;
	}

	private void removeAccount() {
		Editor editor = sharedPrefs.edit();
		editor.remove(Constants.XMPP_USERNAME);
		editor.remove(Constants.XMPP_PASSWORD);

		editor.remove(Constants.XMPP_F_USERNAME);
		editor.remove(Constants.XMPP_F_PASSWORD);
		editor.commit();
	}

	private boolean isRegistered() {
		// 判断该账户有没有注册过
		// return false;
		IMAccount pullAcount = getPullAccount();
		if (pullAcount == null) {
			return false;
		}
		if (!sharedPrefs.contains(Constants.XMPP_USERNAME)
				|| !sharedPrefs.contains(Constants.XMPP_PASSWORD)) {
			return false;
		}
		String s = sharedPrefs.getString(Constants.XMPP_USERNAME, "");
		String s2 = sharedPrefs.getString(Constants.XMPP_PASSWORD, "");
		if (!pullAcount.getUsername().equals(
				sharedPrefs.getString(Constants.XMPP_USERNAME, ""))
				|| !pullAcount.getPassword().equals(
						sharedPrefs.getString(Constants.XMPP_PASSWORD, ""))) {
			return false;
		}
		return true;
	}

	public Chat getChat(String userid) {
		if (xmppManager.isAuthenticated()) {
			return xmppManager.getConnection().getChatManager()
					.createChat(userid, null);
		}else{
			//尝试重连
			int r = login(false);
			if(r == IMManager.AUTH_SUCCESS || r == IMManager.AUTH_ALREAY){
				return xmppManager.getConnection().getChatManager()
						.createChat(userid, null);
			}else{
				return null;
			}
		}
	}

	public boolean isConnected(){
		return xmppManager.isAuthenticated() ;
	}
	public boolean isConnectedWithCheckPackage(){
		boolean flag =  xmppManager.isAuthenticated() ;
		if(flag){
			//在判断包是不是真的能接收到
			return sendHeartBeatPkg();
		}else{
			return false;
		}
	}
	/**
	 * send the message to user
	 * 
	 * @param userid
	 *            ,to user
	 * @param message
	 *            ,the message
	 */
	@SuppressWarnings(value = { "为了保证数据的准备到达，加了服务器信息确认机制，无返回值的该方法只有特殊场景才可以使用" })
//	private int sendMessageToUser(Chat chat, Message message) {
//		if (xmppManager.isAuthenticated()) {
//			try {
//				chat.sendMessage(message);
//				return IMManager.SEND_SUCCESS;
//			} catch (Exception e) {
//				e.printStackTrace();
//				return IMManager.SEND_CONTENT_INVLIDATE;
//			}
//		} else {
//			return IMManager.SEND_CONNECT_RESET;
//		}
//	}

	/**
	 * 发送消息并等待回复确认
	 * 
	 * @param chat
	 * @param message
	 * @param milseconds
	 * @return
	 */
	public int sendMessageToUserWithResult(Chat chat, Message message,
			long milseconds) {
		if (xmppManager.isAuthenticated()) {
			try {
				String s = chat.getParticipant();
				PacketCollector collector = chat.createCollector();
				chat.sendMessage(message);
				Message response = (Message) collector.nextResult(milseconds);

				if (response == null) {
					return IMManager.SEND_CONNECT_RESET;
				} else if (response.getType() == Message.Type.error) {
					return IMManager.SEND_CONNECT_RESET;
				}
				return IMManager.SEND_SUCCESS;
			} catch (Exception e) {
				e.printStackTrace();
				return IMManager.SEND_CONTENT_INVLIDATE;
			}
		} else {
			return IMManager.SEND_CONNECT_RESET;
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param messageId
	 * @param path
	 */
	public void uploadFile(int messageId, String path,
			UploadCompleteListener listener) {
		getUploader().removeFileByOuterId(messageId+"");
		UFile uFile = new UFile();
		uFile.setRemoteFileUri(getUploadUrl());
		uFile.setLocalFileUri(path);
		uFile.setOuterid(messageId + "");
		uFile.setFileParam("file");
		// uFile.setExtralParam(extralParam.toString());
		getUploader().addUFile(uFile);
		getUploader().addUploadCompleteListener(messageId + "", listener);
	}
	/**
	 * 获取聊天记录
	 * 
	 * @return
	 */
	public int getAllMessageOfUser() {
		Message message = new Message();
		message.addExtension(new PacketExtension() {

			@Override
			public String toXML() {
				// TODO Auto-generated method stub
				return "<messagetype namespace=\""+NamespaceC.NAMESPACE_MESSAGE_HISTORY+"\"/>";
			}

			@Override
			public String getNamespace() {
				// TODO Auto-generated method stub
				return NamespaceC.NAMESPACE_MESSAGE_HISTORY;
			}

			@Override
			public String getElementName() {
				// TODO Auto-generated method stub
				return "messagetype";
			}
		});
		Chat chat = getChat(NamespaceC.NAMESPACE_USER_ADMIN);
		return sendMessageToUserWithResult(chat, message,10000);
	}

	/**
	 * 发送文本
	 * 
	 * @param chat
	 * @param base64
	 * @return
	 */
	public void sendText(final Chat chat, final MessageDto messageDto,
			final IMBigDataTransListener listener) {
				Message message = new Message();
				message.addExtension(new PacketExtension() {

					@Override
					public String toXML() {
						// TODO Auto-generated method stub
						return "<messagetype namespace=\""+NamespaceC.NAMESPACE_MESSAGE_TEXT+"\"/>";
					}

					@Override
					public String getNamespace() {
						return NamespaceC.NAMESPACE_MESSAGE_TEXT;
					}

					@Override
					public String getElementName() {
						// TODO Auto-generated method stub
						return "messagetype";
					}
				});
				message.setBody(messageDto.getMessage());
				int r;
				if(chat == null){
					r= IMBigDataTransListener.RESULT_NET_ERROR;
				}else{
					r= sendMessageToUserWithResult(chat, message,
						10000);
				}
				listener.onResult(r);
		
	}
	/**
	 * 发送图片
	 * 
	 * @param chat
	 * @param base64
	 * @return
	 */
	public void sendImage(final Chat chat, final MessageDto messageDto,
			final IMBigDataTransListener listener) {
		if(chat == null){
			listener.onResult(IMBigDataTransListener.RESULT_NET_ERROR);
		}else{
			
		uploadFile(messageDto.getId(), messageDto.getMessage(),
				new UploadCompleteListener() {

					@Override
					public void onError(UFile uFile, String httpResponse) {
						listener.onResult(IMBigDataTransListener.RESULT_NET_ERROR);
					}

					@Override
					public void onComplete(UFile uFile, String httpResponse) {
						try {
							JSONObject json = new JSONObject(httpResponse);
							Message message = new Message();
							message.addExtension(new PacketExtension() {

								@Override
								public String toXML() {
									return "<messagetype namespace=\""+NamespaceC.NAMESPACE_MESSAGE_IMAGE+"\"/>";
								}

								@Override
								public String getNamespace() {
									return NamespaceC.NAMESPACE_MESSAGE_IMAGE;
								}

								@Override
								public String getElementName() {
									return "messagetype";
								}
							});
							message.setBody(json.getString("data"));
							int r = sendMessageToUserWithResult(chat, message,
									10000);
							listener.onResult(r);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
				});
		}
	}

	/**
	 * 发送音频
	 * 
	 * @param chat
	 * @param base64
	 * @return
	 */
	public void sendVoice(final Chat chat, final MessageDto messageDto,
			final IMBigDataTransListener listener) {
		if(chat == null){
			listener.onResult(IMBigDataTransListener.RESULT_NET_ERROR);
		}else{
		uploadFile(messageDto.getId(), messageDto.getMessage(),
				new UploadCompleteListener() {

					@Override
					public void onError(UFile uFile, String httpResponse) {
						listener.onResult(IMBigDataTransListener.RESULT_NET_ERROR);
					}

					@Override
					public void onComplete(UFile uFile, String httpResponse) {
						try {
							JSONObject json = new JSONObject(httpResponse);
							Message message = new Message();
							message.addExtension(new PacketExtension() {

								@Override
								public String toXML() {
									return "<messagetype namespace=\""+NamespaceC.NAMESPACE_MESSAGE_VOICE+"\"/>";
								}

								@Override
								public String getNamespace() {
									return NamespaceC.NAMESPACE_MESSAGE_VOICE;
								}

								@Override
								public String getElementName() {
									return "messagetype";
								}
							});
							message.setBody(json.getString("data"));
							int r = sendMessageToUserWithResult(chat, message,
									10000);
							listener.onResult(r);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
				});
		}

	}

	/**
	 * notification class
	 * 
	 * @return
	 */
	public String getCallbackActivityClassName() {
		return sharedPrefs
				.getString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
	}

	/**
	 * broadcast action
	 * 
	 * @return
	 */
	public String getCallbackBrocastAction() {
		return sharedPrefs.getString(Constants.CALLBACK_BROADCAST_ACTION, "");
	}

	public String getRootActivity() {
		return sharedPrefs.getString(Constants.ROOT_ACTIVITY, "");
	}
	public String getHeartbeatAction() {
		return sharedPrefs.getString(Constants.HEARTBEAT_BROADCAST_ACTION, "");
	}

	public String getUploadUrl() {
		return sharedPrefs.getString(Constants.UPLOAD_URL, "");
	}

	public String getAppName() {
		return sharedPrefs.getString(Constants.APP_NAME, "");
	}

	/**
	 * notification
	 */
	public boolean isNotificationEnabled() {
		return sharedPrefs.getBoolean(Constants.SETTINGS_NOTIFICATION_ENABLED,
				true);
	}

	public boolean isNotificationBroadcastEnabled() {
		return sharedPrefs.getBoolean(Constants.SETTINGS_BROADCAST_ENABLED,
				true);
	}

	public boolean isNotificationSoundEnabled() {
		return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true);
	}

	public boolean isNotificationVibrateEnabled() {
		return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED, true);
	}

	public boolean isNotificationToastEnabled() {
		return sharedPrefs.getBoolean(Constants.SETTINGS_TOAST_ENABLED, true);
	}

	public Uploader getUploader() {
		if (uploader == null) {
			initUploader();
		}
		return uploader;
	}

	public Downloader getDownloader() {
		if (downloader == null) {
			initDownloader();
		}
		return downloader;
	}

	public void initDownloader() {
		if (downloader == null) {
			downloader = new Downloader(context);
			im_file_dir = CorePreferences.getAppSDPathWithSubDir("im");
		}
	}

	public void initUploader() {
		if (uploader == null) {
			uploader = new Uploader(context, new OnServerResponse() {

				@Override
				public boolean isSuccess(String response) {
					try {
						JSONObject json = new JSONObject(response);
						return json.getInt("result") == 1;
					} catch (JSONException e) {
						e.printStackTrace();
						return false;
					}
				}
			});
		}

	}

	public void downloadFile(MessageDto messageDto,DownloadCompleteListener listener){
		DFile dfile =  getDownloader().getDFileByOuterId(messageDto.getId()+"");
		if(dfile == null){
			//添加到下载管理器中
			DFile dFile = new DFile();
			dFile.setRemoteFileUri(messageDto.getMessage());
			
			File localFile = new File(im_file_dir, FileUtil.getFileNameFromUrl(messageDto.getMessage()));
			dFile.setLocalFileUri(localFile
					.getAbsolutePath());
			dFile.setOuterid(messageDto.getId() + "");
			getDownloader().addDFile(dFile);
			getDownloader().addDownloadCompleteListener(messageDto.getId() + "",listener);
		}
		
	}
	public String moveFileToIM(String opath){
		File of = new File(opath);
		File nf = new File(im_file_dir,"local_"+System.currentTimeMillis()+"_"+of.getName());
         int byteread = 0; 
         try {
			if (of.exists()) {
			     InputStream inStream = new FileInputStream(of); //读入原文件 
			     FileOutputStream fs = new FileOutputStream(nf); 
			     byte[] buffer = new byte[1024]; 
			     int length; 
			     while ( (byteread = inStream.read(buffer)) != -1) { 
			         fs.write(buffer, 0, byteread); 
			     } 
			     inStream.close();
			     return nf.getAbsolutePath();
			 }
			return null;
		} catch (Exception e) {
			Log.e(LOGTAG, e.getMessage());
			return null;
		} 
	}
//	public String dealIMImage(String oldpath){
//		int degree = ImageUtil.readPictureDegree(oldpath);
//		
//		//压缩图片
//		try {
//			
//			byte[] data = IOUtil.toByteArray(new FileInputStream(oldpath));
//			BitmapFactory.Options opts = new BitmapFactory.Options();
//			opts.inJustDecodeBounds = true;
//			BitmapFactory.decodeByteArray(data, 0, data.length, opts);
//			double w = opts.outWidth;
//			int sampeSize = mAil.computeSampleSize(opts, imgH,imgH*imgW, mAil.IMAGE_SCALE_TYPE_LOW);
//			opts.inSampleSize = sampeSize;
//			opts.inPreferredConfig = Config.RGB_565;
//			opts.inJustDecodeBounds = false;
//			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
//					opts);
//			mAil.putCacheBitmap(msg, bitmap);
//		}
//			
//	}
	
	public DFile isDownLoaded(MessageDto messageDto){
		return getDownloader().getDFileByOuterId(messageDto.getId()+"");
	}
//	public void destoryUpDownLoader(){
//		getUploader().destory();
//		getDownloader().destory();
//	}
}
